<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use app\common\model\Config;
use app\common\model\MerchantCar;
use fast\Random;
use think\exception\ValidateException;
use think\facade\Db;
use app\common\model\Merchant as MerchatModel;
use think\Model;

/**
 * 商家管理
 *
 * @icon fa fa-circle-o
 */
class Merchant extends Backend
{
    
    /**
     * Merchant模型对象
     * @var \app\common\model\Merchant
     */
    protected $model = null;
//    protected $modelValidate = true;
//    protected $modelSceneValidate = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Merchant;
		$this->view->assign('serviceList',MerchatModel::serviceList());
	    $this->view->assign('statuslist',$this->model->getStatusList());
	    $this->assignconfig('statuslist',$this->model->getStatusList());
	    $this->assignconfig('checkStatuslist',$this->model->getCheckStatusList());
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = $this->request->get("filter");
            $op = $this->request->get("op");
            $tempFilter = json_decode($filter, true) ?? [];
            $tempOp = json_decode($op, true) ?? [];
            $city = '';
            if(isset($filter['city'])){
                $city = $filter['city'];
                unset($tempFilter['add_uid']);
                unset($tempOp['add_uid']);
                $filter = json_encode($tempFilter);
                $op = json_encode($tempOp);
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams(null, null, $filter, $op);
            $builder = $this->model
                ->withCount(['merchant_car', 'merchant_area'])
                ->where($where)
                ->where('is_delete', 1);
            if($this->group_id == 2 && $this->merchant){
                $builder->where('id', $this->merchant['id']);
            }
            if($city){
                $builder->where('province|city|area|street', 'like', '%'.$city.'%');
            }
            $total = $builder
                ->order($sort, $order)
                ->count();
            $list  = $builder
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = ['total' => $total, 'rows' => $list];

            return json($result);
        }

        return $this->view->fetch();
    }


    /**
	 * 添加
	 */
	public function add()
	{
		if ($this->request->isPost()) {
			$params = $this->request->post('row/a');
			if ($params) {
				$params = $this->preExcludeFields($params);

				if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
					$params[$this->dataLimitField] = $this->auth->id;
				}
				$result = false;
				Db::startTrans();

				try {
					//是否采用模型验证
					if ($this->modelValidate) {
						$name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.add' : $name) : $this->modelValidate;
						validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
					}

					if($params['merchant_password']){
                        //密码加密
                        $params['salt'] = Random::alnum();
                        $params['merchant_password'] = MerchatModel::saltPassword($params['merchant_password'],$params['salt']);
                    }else{
                        //密码加密
                        $params['salt'] = Random::alnum();
                        $params['merchant_password'] = MerchatModel::saltPassword($params['merchant_phone'],$params['salt']);
                    }
                    $params['signing_time'] = strtotime($params['signing_time']);

					//省市县重组
//					$cityArr = explode('/',$params['city']);
//					$params['province'] = $cityArr[0];
//					$params['city'] = $cityArr[1];
//					$params['area'] = $cityArr[2];

                    //经纬度
                    $point = explode(',', $params['point']);
                    $params['longitude'] = $point[0];
                    $params['latitude'] = $point[1];

                    //地址
                    $address = getAddress($params['address']);
                    $params['province'] = $address['province'];
                    $params['city'] = $address['city'];
                    $params['area'] = $address['area'];
                    $params['street'] = $address['street'];
                    $params['examine_status'] = 2;
                    $params['service'] = implode(',',$params['service']);

                    $params['open_time'] = $params['day_start_time'] . '-' . $params['day_end_time'];
                    $params['night_time'] = $params['night_start_time'] . '-' . $params['night_end_time'];
                    unset($params['day_start_time'],$params['day_end_time'],$params['night_start_time'],$params['night_end_time']);

					$result = $this->model->save($params);
					$merchant_id = $this->model->id;
					if(!$result){
                        Db::rollback();
                        $this->error('添加失败');
                    }
					//更新商家车辆坐标
                    MerchantCar::where('merchant_id', $merchant_id)->update(['merchant_longitude' => $params['longitude'], 'merchant_latitude' => $params['latitude']]);
                    //添加商家后台管理人员
                    $admin = [
                        'salt' => $params['salt'],
                        'password' => $params['merchant_password'],
                        'username' => $params['merchant_phone'],
                        'nickname' => $params['merchant_name'],
                        'createtime' => time(),
                        'avatar' => $params['shop_logo']
                    ];
                    try {
                        validate('Admin.add')->check($admin);
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    $admin_model = new Admin();
                    $result = $admin_model->save($admin);
                    if (!$result) {
                        Db::rollback();
                        $this->error('添加失败');
                    }
                    $dataset = ['uid' => $admin_model->id, 'group_id' => 2];
                    $auth_group_access_model = new AuthGroupAccess();
                    $res = $auth_group_access_model->save($dataset);
                    if (!$res) {
                        Db::rollback();
                        $this->error('添加失败');
                    }
					Db::commit();
				} catch (ValidateException $e) {
					Db::rollback();
					$this->error($e->getMessage());
				} catch (\PDOException $e) {
					Db::rollback();
					$this->error($e->getMessage());
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
				if ($result !== false) {
					$this->success();
				} else {
					$this->error(__('No rows were inserted'));
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}

		return $this->view->fetch();
	}

	/**
	 * 编辑
	 */
	public function edit($ids = null)
	{
		$row = $this->model->get($ids);
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds)) {
			if (!in_array($row[$this->dataLimitField], $adminIds)) {
				$this->error(__('You have no permission'));
			}
		}
		if ($this->request->isPost()) {
			$params = $this->request->post('row/a');
			if ($params) {
				$params = $this->preExcludeFields($params);
				$result = false;
				Db::startTrans();

				try {
					//是否采用模型验证
					if ($this->modelValidate) {
						$name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
						$validate = is_bool($this->modelValidate) ? $name : $this->modelValidate;
						$pk       = $row->getPk();
						if (!isset($params[$pk])) {
							$params[$pk] = $row->$pk;
						}
						validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
					}
					if (isset($params['merchant_password']) && $params['merchant_password'] != $row['merchant_password'] && $params['merchant_password']){
						//密码加密
						$params['salt'] = Random::alnum();
						$params['merchant_password'] = MerchatModel::saltPassword($params['merchant_password'],$params['salt']);
					}else{
					    unset($params['merchant_password']);
                    }

					if(isset($params['signing_time']) && $params['signing_time']){
                        $params['signing_time'] = strtotime($params['signing_time']);
                    }


//					//省市县重组
//					$cityArr = explode('/',$params['city']);
//					$params['province'] = $cityArr[0];
//					$params['city'] = $cityArr[1];
//					$params['area'] = $cityArr[2];

                    //经纬度
                    if(isset($params['point'])){
                        $point = explode(',', $params['point']);
                        $params['longitude'] = $point[0];
                        $params['latitude'] = $point[1];
                    }


                    //地址
                    if(isset($params['address'])){
                        $address = getAddress($params['address']);
                        $params['province'] = $address['province'];
                        $params['city'] = $address['city'];
                        $params['area'] = $address['area'];
                        $params['street'] = $address['street'];
                    }


					$params['service'] = implode(',',$params['service']);
                    $params['open_time'] = $params['day_start_time'] . '-' . $params['day_end_time'];
                    $params['night_time'] = $params['night_start_time'] . '-' . $params['night_end_time'];
                    unset($params['day_start_time'],$params['day_end_time'],$params['night_start_time'],$params['night_end_time']);
					$result = $row->save($params);
                    if(!$result){
                        Db::rollback();
                        $this->error('编辑失败');
                    }
                    if(isset($params['longitude']) && isset($params['latitude'])){
                        //更新商家车辆坐标
                        MerchantCar::where('merchant_id', $ids)->update(['merchant_longitude' => $params['longitude'], 'merchant_latitude' => $params['latitude']]);
                    }

                    if($this->group_id != 2){
                        //编辑商家后台管理人员
                        $admin_model = new Admin();
                        $admin = $admin_model->field('*')->where('username', $row['merchant_phone'])->find();
                        $new_row = $this->model->get($ids);
                        if($admin){
                            $admin_update = [
                                'salt' => $new_row['salt'],
                                'password' => $new_row['merchant_password'],
                                'username' => $params['merchant_phone'],
                                'nickname' => $params['merchant_name'],
                                'updatetime' => time(),
                                'avatar' => $params['shop_logo'],
                            ];
//                            try {
//                                validate('Admin.edit')->check($admin);
//                            } catch (\Exception $e) {
//                                Db::rollback();
//                                $this->error($e->getMessage());
//                            }
                            $result = $admin_model->where('id', $admin['id'])->update($admin_update);
                            if (!$result) {
                                Db::rollback();
                                $this->error('编辑失败');
                            }
                        }else{
                            $admin = [
                                'salt' => $new_row['salt'],
                                'password' => $new_row['merchant_password'],
                                'username' => $params['merchant_phone'],
                                'nickname' => $params['merchant_name'],
                                'createtime' => time(),
                                'avatar' => $params['shop_logo'],
                            ];
                            try {
                                validate('Admin.add')->check($admin);
                            } catch (\Exception $e) {
                                Db::rollback();
                                $this->error($e->getMessage());
                            }
                            $result = $admin_model->save($admin);
                            $dataset = ['uid' => $admin_model->id, 'group_id' => 2];
                            $auth_group_access_model = new AuthGroupAccess();
                            $res = $auth_group_access_model->save($dataset);
                            if (!$res) {
                                Db::rollback();
                                $this->error('编辑失败');
                            }
                            if (!$result) {
                                Db::rollback();
                                $this->error('编辑失败');
                            }
                        }
                    }


					Db::commit();
				} catch (ValidateException $e) {
					Db::rollback();
					$this->error($e->getMessage());
				} catch (\PDOException $e) {
					Db::rollback();
					$this->error($e->getMessage());
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
				if ($result !== false) {
					$this->success();
				} else {
					$this->error(__('No rows were updated'));
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
        $row['address'] = $row['province'] . $row['city'] . $row['area'] . $row['street'];
		if($row['longitude'] && $row['latitude']){
            $row['point'] = $row['longitude'].','.$row['latitude'];
        }
		$open_time = explode('-', $row['open_time']);
		$night_time = explode('-', $row['night_time']);
		//商家价格区域
        $area_list = \app\admin\model\MerchantArea::where(['is_delete' => 1, 'merchant_id' => $ids])->column('area');
        $areaList = [];
        if($area_list){
            foreach ($area_list as $k=>$v){
                $merchantAreas = [];
                if($v){
                    $newVal = explode(';',$v);
                    foreach ($newVal as $ks=>$vs){
                        $newvals = explode(',',$vs);
                        $merchantAreas[] = [
                            $newvals[0],
                            $newvals[1]
                        ];
                    }
                    $areaList[] = $merchantAreas;
                }
            }
        }
        $row['day_start_time'] = $open_time[0]??'';
        $row['day_end_time'] = $open_time[1]??'';
        $row['night_start_time'] = $night_time[0]??'';
        $row['night_end_time'] = $night_time[1]??'';
        $row['shop_banner_list'] = $row['shop_banner'] ? explode(',', $row['shop_banner']) : [];
		$this->view->assign('row', $row);
        $this->view->assign('areaList', json_encode($areaList));

		return $this->view->fetch();
	}

	/**
	 * 详情.
	 */
	public function detail($ids)
	{
		$row = $this->model->find(['id' => $ids]);
		if (! $row) {
			$this->error(__('No Results were found'));
		}
		$service_data = '';
		if($row['service']){
            $service_list = explode(',', $row['service']);
            foreach ($service_list as $key => $value){
                $service_list[$key] = MerchatModel::serviceList($value);
            }
            $service_data = implode(',', $service_list);
        }
//		$row['notice'] = Config::where('name', 'notice')->value('value');
		$row['shop_banner'] = explode(',', $row['shop_banner']);
		$row->status = $this->model->getStatusList($row->status);
		$row->examine_status = $this->model->getCheckStatusList($row->examine_status);
		$row->service_data = $service_data;
		$this->view->assign('row', $row->toArray());
		return $this->view->fetch();
	}

	//店铺审核
	public function check(){

		if ($this->request->isAjax()){
			if ($this->request->isPost()){
				$params = $this->request->param();
				if (!count($params)){
					$this->error('参数错误');
				}else{
					$status = $params['status'];
					$ids = $params['ids'];
					if ($status == 2 | $status == 3){

						$result = false;
						Db::startTrans();
						try {
							$statusIds = $this->model->where('id', 'in', $ids)->column('examine_status');
							if (in_array(2, $statusIds) || in_array(3, $statusIds)) {
								$this->error(__('您选择的数据有已审核数据，不能再次审核'));
							}
                            $signingTimes = $this->model->where('id', 'in', $ids)->whereNull('signing_time')->count();
                            if ($status == 2 && $signingTimes) {
                                $this->error(__('请先设置商家的签约时间'));
                            }
							$phoneArr = MerchatModel::where(['id' => $ids])->column('merchant_phone','id');
							foreach ($ids as $k=>$v){
								//密码加密
								$salt = Random::alnum();
								$password = MerchatModel::saltPassword($phoneArr[$v],$salt);
								$result = MerchatModel::where(['id' => $v])->update(['examine_status' => $status,'merchant_password' => $password,'salt' => $salt]);
								if($status == 2){
                                    $merchant = $this->model->field('id,salt,merchant_phone,merchant_password,merchant_name,shop_logo')->where('id', $v)->find();
                                    //添加商家后台管理人员
                                    $admin = [
                                        'salt' => $merchant['salt'],
                                        'password' => $merchant['merchant_password'],
                                        'username' => $merchant['merchant_phone'],
                                        'nickname' => $merchant['merchant_name'],
                                        'createtime' => time(),
                                        'avatar' => $merchant['shop_logo']
                                    ];
                                    try {
                                        validate('Admin.add')->check($admin);
                                    } catch (\Exception $e) {
                                        Db::rollback();
                                        $this->error($e->getMessage());
                                    }
                                    $admin_model = new Admin();
                                    $result = $admin_model->save($admin);
                                    if (!$result) {
                                        Db::rollback();
                                        $this->error('添加失败');
                                    }
                                    $dataset = ['uid' => $admin_model->id, 'group_id' => 2];
                                    $auth_group_access_model = new AuthGroupAccess();
                                    $res = $auth_group_access_model->save($dataset);
                                    if (!$res) {
                                        Db::rollback();
                                        $this->error('添加失败');
                                    }
                                }
							}
							Db::commit();
						} catch (ValidateException $e) {
							Db::rollback();
							$this->error($e->getMessage());
						} catch (PDOException $e) {
							Db::rollback();
							$this->error($e->getMessage());
						} catch (Exception $e) {
							Db::rollback();
							$this->error($e->getMessage());
						}
						if ($result !== false) {
							$this->success('审核成功');
						} else {
							$this->error(__('No rows were inserted'));
						}
					}else{
						$this->error('参数错误');
					}
				}
			}
		}

	}

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $merchant_cars = \app\api\model\MerchantCar::where(['is_delete' => 1, 'examine_status' => [1,2]])->whereIn('merchant_id', $ids)->count();
        if($merchant_cars){
            $this->error(__('该商家下有运营车辆'));
        }
        $this->model->where('id', 'in', $ids)->update(['is_delete' => 2, 'deletetime' => time()]);
        $admin =  Admin::where('username', $row['merchant_phone'])->find();
        if($admin){
            Admin::where('id', $admin['id'])->delete();
            AuthGroupAccess::where('uid', $admin['id'])->delete();
        }
        $this->success();
    }


}
